package com.aisino.mvpdesignproject2.http.rxjava;

import com.aisino.mvpdesignproject2.constant.AppConstants;
import com.aisino.mvpdesignproject2.http.exception.ApiException;
import com.aisino.mvpdesignproject2.http.itf.Stateful;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * @author houhouiswho
 * @date 2018/9/4
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<T>{

    private Disposable disposable;
    private Stateful target;

    public void setTarget(Stateful target) {
        this.target = target;
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.disposable = d;
        onSubcribes(d);

    }

    @Override
    public void onNext(T model) {
        LogUtils.e(model.toString());
        target.setState(AppConstants.STATE_SUCCESS);
        onSuccess((T) model);
        return;

//        ApiException e = new ApiException(model.getError_code(), model.getReason());
//        onError(e);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        LogUtils.e(e.getMessage());
        String errorMsg = null;
        target.setState(AppConstants.STATE_ERROR);
        //没有网络，请求失败
        if (e instanceof IOException) {
            errorMsg = "Please Check Your Net!!";
            // 网络异常，http 请求失败，即 http 状态码不在 [200, 300) 之间, such as: "server internal error".
        } else if (e instanceof HttpException) {
            HttpException exception = (HttpException) e;
            try {
                String json = exception.response().errorBody().string();
                Gson gson = new Gson();
//                BaseBean data = gson.fromJson(json, BaseBean.class);
//                errorMsg = data.getReason();

            } catch (IOException e1) {
                e1.printStackTrace();
                errorMsg = e1.getMessage();
            }
            //网络正常，http 请求成功，服务器返回逻辑错误
        } else if (e instanceof ApiException) {
            errorMsg = ((ApiException) e).getMsg();
            //其他未知错误
        } else {
            errorMsg = "Unknown Error";
        }
        LogUtils.e(errorMsg);
        onFailed(errorMsg);

    }

    @Override
    public void onComplete() {
    }


    /**
     * Request a successful callback
     *
     * @param t
     */
    public abstract void onSuccess(T t);

    /**
     * Request failed callback
     *
     * @param msg
     */
    public abstract void onFailed(String msg);

    /**
     * Add Disposable for easy administration
     *
     * @param d
     */
    public abstract void onSubcribes(Disposable d);
}